<script lang="ts" setup>
import { injectState } from "../state";
import * as Cesium from "cesium";
import { useUserStore } from "@/stores/user";
import bus from "vue3-eventbus";
import {
	whManagerBsTbParkGridGetListUsingPost,
	whManagerBsTbParkGridDeleteByIdIdUsingPost,
} from "@/genapi/wh";
import Entity from "cesium/Source/DataSources/Entity";

defineOptions({ name: "Headler" });

bus.on("clearGridData", (val) => {
	clearGridData();
});

bus.on("updateGridData", () => {
	userStore.viewer.entities.removeAll();
	tempEntities.value = [];
	tempPolygon.value = null;
	getGridList();
});

const userStore = useUserStore();

const { selectedList, tableRef, detailDialogRef } = injectState()!;

const tempEntities = ref([]);

const tempPolygon = <any>ref(null);

const clearGridData = () => {
	let viewer = userStore.viewer;
	tempEntities.value.forEach((item) => {
		viewer.entities.remove(item);
	});
	viewer.entities.remove(tempPolygon.value);
	tempEntities.value = [];
	tempPolygon.value = null;
	//   // 清除之前的实体
	//   const entitys = viewer.entities._entities._array;
	//   let length = entitys.length
	//   // 倒叙遍历防止实体减少之后entitys[f]不存在
	//   for (let f = length - 1; f >= 0; f--) {
	//     if (entitys[f]._name && (entitys[f]._name === '点几何对象' || entitys[f]._name === '线几何对象' || entitys[f]._name === '面几何对象')) {
	//       viewer.entities.remove(entitys[f]);
	//     }
	//   }
};

const addGrid = () => {
	let viewer = userStore.viewer;
	let position = [];
	let tempPoints = [];
	let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
	//鼠标移动事件
	handler.setInputAction(function (
		movement,
	) {}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	//左键点击操作
	handler.setInputAction(function (click) {
		//调用获取位置信息的接口
		let ray = viewer.camera.getPickRay(click.position);
		position = viewer.scene.globe.pick(ray, viewer.scene);
		tempPoints.push(position);
		let tempLength = tempPoints.length;
		//调用绘制点的接口
		let point = drawPoint(position);
		tempEntities.value.push(point);
		if (tempLength > 1) {
			let pointline = drawPolyline([
				tempPoints[tempPoints.length - 2],
				tempPoints[tempPoints.length - 1],
			]);
			tempEntities.value.push(pointline);
		} else {
			// tooltip.innerHTML = "请绘制下一个点，右键结束";
		}
	}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	//右键点击操作
	handler.setInputAction(function (click) {
		let cartesian = viewer.camera.pickEllipsoid(
			click.position,
			viewer.scene.globe.ellipsoid,
		);

		if (cartesian) {
			let tempLength = tempPoints.length;
			if (tempLength < 3) {
				ElMessage.info("请选择3个以上的点再执行闭合操作命令");
			} else {
				//闭合最后一条线
				let pointline = drawPolyline([
					tempPoints[tempPoints.length - 1],
					tempPoints[0],
				]);
				tempEntities.value.push(pointline);
				tempPolygon.value = drawPolygon(tempPoints);
				tempEntities.value.push(tempPoints);
				handler.destroy(); //关闭事件句柄
				handler = null;
				setTimeout(() => {
					detailDialogRef?.value.trigger("write");
					bus.emit("getGridData", tempPoints);
					tempEntities.value.forEach((item) => {
						userStore.viewer.entities.remove(item);
					});
					tempEntities.value = [];
					tempPolygon.value = null;
				}, 1000);
			}
		}
	}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};

const drawPoint = (position, config) => {
	let viewer = userStore.viewer;
	let config_ = config ? config : {};
	return viewer.entities.add({
		name: "点几何对象",
		position: position,
		point: {
			color: Cesium.Color.SKYBLUE,
			pixelSize: 10,
			outlineColor: Cesium.Color.YELLOW,
			outlineWidth: 3,
			disableDepthTestDistance: Number.POSITIVE_INFINITY,
			heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
		},
	});
};

const drawPolyline = (positions, config_) => {
	let viewer = userStore.viewer;
	if (positions.length < 1) return;
	let config = config_ ? config_ : {};
	return viewer.entities.add({
		name: "线几何对象",
		polyline: {
			positions: positions,
			width: config.width ? config.width : 5.0,
			material: new Cesium.PolylineGlowMaterialProperty({
				color: config.color
					? new Cesium.Color.fromCssColorString(config.color)
					: Cesium.Color.GOLD,
			}),
			depthFailMaterial: new Cesium.PolylineGlowMaterialProperty({
				color: config.color
					? new Cesium.Color.fromCssColorString(config.color)
					: Cesium.Color.GOLD,
			}),
			clampToGround: true,
		},
	});
};

const drawPolygon = (positions, details) => {
	let viewer = userStore.viewer;
	if (positions.length < 2) return;
	return viewer.entities.add({
		id: details ? details.id : "",
		name: "面几何对象",
		position: Cesium.BoundingSphere.fromPoints(positions).center,
		label: {
			text: details ? details.name : "",
			fillColor: Cesium.Color.WHITE,
			font: "14pt Source Han Sans CN",
			show: true,
			disableDepthTestDistance: Number.POSITIVE_INFINITY,
			outline: true,
			outlineColor: Cesium.Color.BLACK,
			outlineWidth: 10,
		},
		polygon: {
			hierarchy: positions,
			material: new Cesium.Color.fromCssColorString("#FFD700").withAlpha(0.4),
		},
	});
};

const gridList = <any>ref([]);

const getGridList = async () => {
	const { data } = await whManagerBsTbParkGridGetListUsingPost({
		data: {},
	});
	gridList.value = data;
	data?.forEach((item) => {
		if (item.coordinatePoints) {
			drawPolygon(JSON.parse(item.coordinatePoints), item);
		}
	});
};

const selectGrid = (type) => {
	var handler = new Cesium.ScreenSpaceEventHandler(
		userStore.viewer.scene.canvas,
	);
	//拾取坐标
	handler.setInputAction(function onLeftClick(movement) {
		// 获取点击的位置
		var pickedObject = userStore.viewer.scene.pick(movement.position);
		// 判断是否选中了一个实体
		if (
			Cesium.defined(pickedObject) &&
			pickedObject.id instanceof Cesium.Entity
		) {
			var entity = pickedObject.id;
			if (entity._name === "面几何对象") {
				if (type === "delete") {
					deleteGrid(entity);
				} else {
					editGrid(entity);
				}
				// userStore.viewer.entities.remove(entity);
			}
			handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
		} else {
			ElMessage.info("取消操作");
			handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
		}
	}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
};

const deleteGrid = async (entity) => {
	await ElMessageBox.confirm("确认删除该网格吗？", "提示", {
		type: "warning",
	});
	await whManagerBsTbParkGridDeleteByIdIdUsingPost({
		path: {
			id: entity.id,
		},
	});
	userStore.viewer.entities.remove(entity);
	ElMessage.success("删除成功");
};

const editGrid = (entity) => {
	const element = gridList.value.filter((item) => item.id === entity.id);
	detailDialogRef?.value.trigger("write", element[0]);
	bus.emit("getGridData", JSON.parse(element[0].coordinatePoints));
};

onMounted(() => {
	getGridList();
});
</script>

<template>
	<div class="handlerContent" flex="~ justify-between">
		<div flex="~">
			<!-- <el-button type="primary" @click="detailDialogRef?.trigger('write')">
				<template #icon>
					<el-icon class="i-custom:save" />
				</template>
				保存
			</el-button> -->
			<el-button type="primary" @click="selectGrid('delete')">
				<template #icon>
					<el-icon class="i-custom:delete" />
				</template>
				删除
			</el-button>
			<el-button type="primary" @click="selectGrid('edit')">
				<template #icon>
					<el-icon class="i-custom:edit" />
				</template>
				编辑
			</el-button>
			<el-button type="primary" @click="addGrid">
				<template #icon>
					<el-icon class="i-custom:add" />
				</template>
				新增
			</el-button>
		</div>
	</div>
</template>

<style lang="scss" scoped>
.handlerContent {
	position: absolute;
	top: 10px;
	right: 10px;
	z-index: 999;
}
</style>
